package com.devo.icecream.ui.diy

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.devo.icecream.R
import com.devo.icecream.data.IngredientsBean
import com.devo.icecream.ui.theme.Grey
import com.devo.icecream.ui.theme.Main
import com.devo.icecream.ui.theme.Pink
import com.devo.icecream.ui.theme.textGreyColor
import com.devo.icecream.utils.noRippleClickable
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

@Composable
internal fun IngredientsLayout(
    selectIds: List<Int> = listOf(),
    list: Map<Category, List<IngredientsBean>> = mapOf(),
    onSelectItem: (id: Int) -> Unit = {}
) {
    Box(
        modifier = Modifier
            .clip(RoundedCornerShape(16.dp))
            .background(Color.White),
    ) {
        LazyColumn(
            modifier = Modifier.fillMaxSize(),
            contentPadding = PaddingValues(horizontal = 24.dp)
        ) {
            itemsIndexed(list.keys.toList()) { inx, key ->
                list[key]?.takeIf { it.isNotEmpty() }?.let {
                    if (inx > 0) {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .background(Grey)
                                .height(3.dp)
                        )
                    }
                    IngredientsGroup(
                        name = key.name,
                        list = it,
                        selectIds = selectIds,
                        onSelectItem = onSelectItem
                    )
                }

            }
        }

    }
}

@Composable
private fun IngredientsGroup(
    name: String,
    list: List<IngredientsBean>,
    selectIds: List<Int> = listOf(),
    onSelectItem: (id: Int) -> Unit = {}
) {
    Column(
        modifier = Modifier
            .fillMaxWidth(),
        horizontalAlignment = Alignment.Start
    ) {

        Text(
            modifier = Modifier
                .padding(vertical = 24.dp)
                .padding(start = 16.dp),
            text = name,
            style = MaterialTheme.typography.h3
        )

        Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
            list.chunked(3).map { ls ->
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    for (inx in 0..2) {

                        val item = ls.getOrNull(inx)

                        if (item == null) {

                            Spacer(modifier = Modifier.weight(1f))

                        } else {

                            IngredientsItem(
                                modifier = Modifier.weight(1f),
                                bean = item,
                                isSelected = selectIds.count { it == item.id } > if (item.allowRepeat) 1 else 0,
                                onSelect = {
                                    onSelectItem(item.id)
                                },
                            )
                        }
                    }
                }
            }
        }

    }
}

@Composable
private fun IngredientsItem(
    modifier: Modifier = Modifier,
    bean: IngredientsBean,
    isSelected: Boolean = false,
    onSelect: () -> Unit = {}
) {

    Column(
        modifier = modifier
            .noRippleClickable { if (bean.isAvailable) onSelect() }
            .wrapContentHeight(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.SpaceAround
    ) {

        Box(
            modifier = Modifier
                .clip(RoundedCornerShape(8.dp))
                .height(IntrinsicSize.Max)
                .width(IntrinsicSize.Max)
        ) {


            AsyncImage(
                modifier = Modifier
                    .background(Grey)
                    .aspectRatio(1f),
                model = bean.picture,
                placeholder = painterResource(id = R.mipmap.cake),
                contentScale = ContentScale.Crop,
                contentDescription = "",
                alpha = if (isSelected) 0.5f else 1f
            )

            if (bean.canRepeat > 0) {
                Box(
                    modifier = Modifier
                        .padding(4.dp)
                        .align(Alignment.BottomEnd)
                ) {
                    Text(
                        modifier = Modifier
                            .background(color = Pink, shape = RoundedCornerShape(30.dp))
                            .padding(vertical = 4.dp, horizontal = 16.dp),
                        text = "可选双份",
                        fontSize = 16.sp,
                        color = Color.White
                    )
                }
            }

            if (!bean.isAvailable) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color.White.copy(0.5f))
                ) {
                    Image(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(24.dp)
                            .wrapContentHeight()
                            .align(Alignment.Center),
                        painter = painterResource(id = R.mipmap.ample),
                        contentScale = ContentScale.FillWidth,
                        contentDescription = "ample"
                    )
                }

            }

        }

        Spacer(modifier = Modifier.height(16.dp))

        Text(
            text = bean.name,
            style = MaterialTheme.typography.body1.copy(fontWeight = FontWeight.Bold)
        )

        Text(
            buildAnnotatedString {
                withStyle(SpanStyle(fontSize = MaterialTheme.typography.body2.fontSize)) {
                    append("￥")
                }
                append(bean.price.toString())
            },
            style = MaterialTheme.typography.body1.copy(color = Main)
        )

        Text(
            "%sKcal".format(bean.power),
            style = MaterialTheme.typography.body1.copy(color = textGreyColor)
        )

        Spacer(modifier = Modifier.height(16.dp))
    }

}


@OptIn(ExperimentalFoundationApi::class)
@Preview(heightDp = 2000, widthDp = 1440)
@Composable
private fun ItemPreview() {

    val json = " [\n" +
            "            {\n" +
            "                \"id\": 8,\n" +
            "                \"name\": \"蜂蜜\",\n" +
            "                \"picture\": \"http://120.78.159.86:6689/file/202206/bc0cea8ce30439c0d301d49d293bc77c.jpg\",\n" +
            "                \"categoryId\": 11,\n" +
            "                \"categoryName\": \"蜂蜜\",\n" +
            "                \"canRepeat\": 1,\n" +
            "                \"remark\": \"\",\n" +
            "                \"validFlag\": null,\n" +
            "                \"price\": 28,\n" +
            "                \"power\": \"25\",\n" +
            "                \"num\": 0,\n" +
            "                \"weight\": 12.0,\n" +
            "                \"bucket\": \"P1\",\n" +
            "                \"chooseNum\": 1,\n" +
            "                \"isMust\": 1,\n" +
            "                \"sort\": 20\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": 12,\n" +
            "                \"name\": \"希腊酸奶\",\n" +
            "                \"picture\": \"http://120.78.159.86:6689/file/202206/2526a32fbba44aee63c806800d094de5.jpg\",\n" +
            "                \"categoryId\": 1,\n" +
            "                \"categoryName\": \"酸奶\",\n" +
            "                \"canRepeat\": 0,\n" +
            "                \"remark\": \"\",\n" +
            "                \"validFlag\": null,\n" +
            "                \"price\": 350,\n" +
            "                \"power\": \"180\",\n" +
            "                \"num\": 0,\n" +
            "                \"weight\": 25.0,\n" +
            "                \"bucket\": \"D6\",\n" +
            "                \"chooseNum\": 1,\n" +
            "                \"isMust\": 1,\n" +
            "                \"sort\": 19\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": 4,\n" +
            "                \"name\": \"普通风味酸奶\",\n" +
            "                \"picture\": \"http://120.78.159.86:6689/file/202206/68c5a96bbe2f08f24897ccd0e427f92b.jpg\",\n" +
            "                \"categoryId\": 1,\n" +
            "                \"categoryName\": \"酸奶\",\n" +
            "                \"canRepeat\": 1,\n" +
            "                \"remark\": \"普通味道\",\n" +
            "                \"validFlag\": null,\n" +
            "                \"price\": 290,\n" +
            "                \"power\": \"150\",\n" +
            "                \"num\": 0,\n" +
            "                \"weight\": 25.0,\n" +
            "                \"bucket\": \"D5\",\n" +
            "                \"chooseNum\": 1,\n" +
            "                \"isMust\": 1,\n" +
            "                \"sort\": 18\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": 9,\n" +
            "                \"name\": \"巧克力酱\",\n" +
            "                \"picture\": \"http://120.78.159.86:6689/file/202206/6e92b661ea56c39a0d91845e69ce01ec.jpg\",\n" +
            "                \"categoryId\": 8,\n" +
            "                \"categoryName\": \"酱汁\",\n" +
            "                \"canRepeat\": 0,\n" +
            "                \"remark\": \"\",\n" +
            "                \"validFlag\": null,\n" +
            "                \"price\": 39,\n" +
            "                \"power\": \"20\",\n" +
            "                \"num\": 0,\n" +
            "                \"weight\": 12.0,\n" +
            "                \"bucket\": \"D2\",\n" +
            "                \"chooseNum\": 1,\n" +
            "                \"isMust\": 1,\n" +
            "                \"sort\": 15\n" +
            "            }" +
            "]"


    val list = Gson().fromJson<List<IngredientsBean>>(
        json,
        object : TypeToken<List<IngredientsBean>>() {}.type
    )
}

